package com.xtravel.tweet.fragment;


import android.content.Intent;
import android.os.*;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.*;
import android.widget.ImageView.ScaleType;
import cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.PauseOnScrollListener;
import com.xtravel.R;
import com.xtravel.common.activity.BrowserActivity;
import com.xtravel.common.constant.BrowserOpenType;
import com.xtravel.common.fragment.BaseFragment;
import com.xtravel.common.widget.AsyncImageView;
import com.xtravel.tweet.adapter.TweetListAdapter;
import com.xtravel.tweet.api.AdvertiseJson;
import com.xtravel.tweet.api.AdvertisementRequest;
import com.xtravel.tweet.database.dao.AdvertiseDao;
import com.xtravel.tweet.database.dto.Tweet;
import com.xtravel.tweet.database.po.Advertise;


import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;

public class TweetFragment extends BaseFragment {
    // private LoadingDialog loadingDialog;
    private TweetListAdapter dataAdapter;
    private PullToRefreshListView pullToRefreshListView;
    private View headerView;
    private AutoScrollViewPager headervViewPager;
    private ViewGroup headerIconGroupView;
    private ImageView[] iconViews;
    private List<View> headerImgViews = new ArrayList<View>();
    private int headerImageIndex = 0;
    private int imageViewActualCount;
    private ScheduledExecutorService autoPlayExecutorService;
    private ILoadingLayout startLabels;
    private LinearLayout signin;

    private OnPageChangeListener headerChangeListener = new OnPageChangeListener() {
        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int index) {
            index = index % imageViewActualCount;
            for (int i = 0; i < iconViews.length; i++) {
                iconViews[i].setBackgroundResource(
                        i == index ? R.drawable.page_indicator_focused : R.drawable.page_indicator_unfocused);
            }
        }
    };

    private PagerAdapter headerPagerAdapter = new PagerAdapter() {
        @Override
        public int getCount() {
            return imageViewActualCount > 1 ? Integer.MAX_VALUE : 1;
        }

        @Override
        public boolean isViewFromObject(View view, Object obj) {
            return view == obj;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            try {
                ((ViewPager) container).addView(headerImgViews.get(position % headerImgViews.size()), 0);
            } catch (Exception e) {
            }

            if (headerImgViews.size() <= 0) {
                return 0;
            }

            return headerImgViews.get(position % headerImgViews.size());
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            if (imageViewActualCount == 2 || imageViewActualCount == 3) {
                return;
            }
            ((ViewPager) container).removeView(headerImgViews.get(position % headerImgViews.size()));
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {
        }

        @Override
        public void startUpdate(View arg0) {
        }


    };

    private Handler dataCallBackHanlder = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            pullToRefreshListView.onRefreshComplete();
            /*
            if (loadingDialog != null)
                loadingDialog.dismiss();
            */
        }
    };
    private BitmapUtils bitmapUtils;

    public TweetFragment() {
        super(R.layout.tweet_main_fragment);
    }

    @Override
    public void onFragmentChange(boolean isChange) {
        if (!isChange) {
            pullToRefreshListView.getRefreshableView().setSelection(0);
            pullToRefreshListView.setRefreshing(false);
            //pullToRefreshListView.onManualRefresh();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        if (isFirstLoad) {
            // loading
            /*
            loadingDialog = new LoadingDialog(getActivity());
            loadingDialog.setCanceledOnTouchOutside(false);
            loadingDialog.show();
            */
            // set dataAdapter

            View footerView = View.inflate(getActivity(), R.layout.footer_tweet, null);
            pullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.tweet_list);
            pullToRefreshListView.getRefreshableView().addFooterView(footerView);
            pullToRefreshListView.getRefreshableView().setBackgroundResource(R.drawable.no_data_loading);

            this.bitmapUtils = new BitmapUtils(getActivity());
            dataAdapter = new TweetListAdapter(this,getActivity(), pullToRefreshListView, footerView, new ArrayList<Tweet>(), this.bitmapUtils, dataCallBackHanlder);

            pullToRefreshListView.setAdapter(dataAdapter);

            startLabels = pullToRefreshListView.getLoadingLayoutProxy(true, false);
            startLabels.setPullLabel("正在刷新...");
            startLabels.setRefreshingLabel("正在刷新...");
            startLabels.setReleaseLabel("正在刷新...");
            ILoadingLayout endLabels = pullToRefreshListView.getLoadingLayoutProxy(false, false);
            endLabels.setPullLabel("正在刷新...");
            endLabels.setRefreshingLabel("正在刷新...");
            endLabels.setReleaseLabel("正在刷新...");
            // header listview
            ListView listView = pullToRefreshListView.getRefreshableView();
            headerView = inflater.inflate(R.layout.tweet_main_list_header, null);

            listView.setOnScrollListener(new PauseOnScrollListener(bitmapUtils, true, true, new AbsListView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {

                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                    if (firstVisibleItem + visibleItemCount + 3 > totalItemCount && firstVisibleItem > 0) {
                        dataAdapter.getData(false);
                    }
                }
            }));

            bindPullListViewRefreshEvent();
            headervViewPager = (AutoScrollViewPager) headerView.findViewById(R.id.headerImgPager);
            headerIconGroupView = (ViewGroup) headerView.findViewById(R.id.headerIconGroup);
        }

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (isFirstLoad) {
            isFirstLoad = false;
            dataAdapter.getData(true);
            // 获取header图片
            getHeaderImages();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (headervViewPager != null) {
            headervViewPager.stopAutoScroll();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (headervViewPager != null) {
            headervViewPager.startAutoScroll();
        }
    }

    private void bindPullListViewRefreshEvent() {
        // 设置PullToRefresh
        pullToRefreshListView.setMode(Mode.PULL_FROM_START);
        pullToRefreshListView.setOnRefreshListener(new OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 下拉的时获取最新的数据
                dataAdapter.getData(true);
            }

            // Pulling Up
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 上拉获取旧数据
                dataAdapter.getData(false);
            }
        });
    }

    private void getHeaderImages() {

        new AsyncTask<Void, Void, AdvertiseJson>() {

            @Override
            protected AdvertiseJson doInBackground(Void... params) {
                AdvertisementRequest request = new AdvertisementRequest();
                return request.get(0, 3);
            }

            @Override
            protected void onPostExecute(AdvertiseJson advertiseJson) {
                pullToRefreshListView.getRefreshableView().addHeaderView(headerView);

                AdvertiseDao dao = new AdvertiseDao(getActivity());
                List<Advertise> advertiseList = new ArrayList<Advertise>();
                if (advertiseJson != null && advertiseJson.getResult().size() > 0) {
                    advertiseList = advertiseJson.getResult();
                    try {
                        dao.saveAll(advertiseList);
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        advertiseList = dao.getAll();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }

                setHeaderImages(advertiseList);
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

        // ApiRequestParam apiRequestParam = new ApiRequestParam("", null);
        // AsyncApiDataTask<List<TweetSource>> apiDataTask = new
        // AsyncApiDataTask<List<TweetSource>>(new Handler(){
        // @Override
        // public void handleMessage(Message msg) {
        // super.handleMessage(msg);
        // List<TweetSource> imgs = (List<TweetSource>) msg.obj;
        // setHeaderImages(imgs);
        // }
        //
        // }, new TypeToken<BaseJson<List<TweetSource>>>() {
        // });
        // apiDataTask.execute(apiRequestParam);
    }

    private void setHeaderImages(final List<Advertise> images) {
        try {
            if (images.size() > 1)
                headerView.setVisibility(View.VISIBLE);
            imageViewActualCount = images.size();
            int paperCount = images.size();
            //2张图片时需要增加至4张才可以达到无缝轮播的效果
            if (imageViewActualCount == 2) {
                paperCount = 4;
            }
            iconViews = new ImageView[paperCount];
            for (int i = 0; i < paperCount; i++) {
                AsyncImageView imgView = new AsyncImageView(getActivity());
                final Advertise ad = images.get(i + 1 > imageViewActualCount ? i % imageViewActualCount : i);
                final String title = ad.getName();
                final String typeName = ad.getTypeName();
                final String httpUrl = ad.getAdUrl();
                final String imageUrl = ad.getPictureUrl();
                final String shareContent = ad.getContent();
                imgView.setImageUrl(imageUrl);
                imgView.setScaleType(ScaleType.CENTER_CROP);
                imgView.setBackgroundColor(getResources().getColor(R.color.color_white));
                imgView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
                imgView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), BrowserActivity.class);
                        intent.putExtra("url", httpUrl);
                        intent.putExtra("shareurl", httpUrl);
                        intent.putExtra("title", title);
                        intent.putExtra("content", shareContent);
                        intent.putExtra("sharetitle", String.format(getResources().getString(R.string.share_ad_title), typeName));
                        intent.putExtra("opentype", BrowserOpenType.Link_Hotel_Ad);
                        ArrayList<String> imgs = new ArrayList<>();
                        imgs.add(imageUrl);
                        intent.putStringArrayListExtra("imgurl", imgs);
                        startActivity(intent);
                    }
                });

                headerImgViews.add(imgView);
                ImageView iconImg = new ImageView(getActivity());
                iconViews[i] = iconImg;
                if (i + 1 > imageViewActualCount) {
                    iconViews[i].setVisibility(View.GONE);
                }
                int resId = i == 0 ? R.drawable.page_indicator_focused : R.drawable.page_indicator_unfocused;
                iconImg.setBackgroundResource(resId);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                headerIconGroupView.addView(iconImg, layoutParams);
            }
            WindowManager wm = getActivity().getWindowManager();
            int width = wm.getDefaultDisplay().getWidth();
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, (int) (width * 6.5 / 16));
            headervViewPager.setLayoutParams(params);
            headervViewPager.setAdapter(headerPagerAdapter);
            headervViewPager.setInterval(3000);
            headervViewPager.startAutoScroll();
            headervViewPager.setCycle(true);
            headervViewPager.setCurrentItem(Integer.MAX_VALUE / 2 - Integer.MAX_VALUE / 2 % headerImgViews.size());

            // 设置监听
            headervViewPager.setOnPageChangeListener(headerChangeListener);
        } catch (Exception e) {
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        dataAdapter.notifyDataSetChanged();
        super.onActivityResult(requestCode, resultCode, data);
    }
}
